/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
  Alert,
  Dimensions,
  Image,
  Modal,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';

import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import Toast from './component/Toast';
import Loading from './component/Loading';
import SelfadaptModal from 'react-native-selfadapt-modal';
import getStyles from '../style/styles';
import axiosInstance, {getUrl, uploadFile} from './utils/request';
import {launchCamera} from 'react-native-image-picker';
import {
  PERMISSIONS,
  check,
  request,
  requestMultiple,
} from 'react-native-permissions';
import RNFetchBlob from 'rn-fetch-blob';
import apiPath from './utils/apiPath';

//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;
var width = WIN_WIDTH / 2;

const TextButton = ({title, onPress}) => {
  return (
    <TouchableOpacity
      style={style.saveBtn}
      underlayColor="transparent"
      onPress={onPress}>
      <Text style={styles.saveText}>{title}</Text>
    </TouchableOpacity>
  );
};

const menuItem = [{flag: 'CustInfoEditScene', name: '用水记录'}];

let styles = {};
export default class Entry extends Component {
  navOptions = () => {
    const {navigation, route} = this.props;
    return {
      title: '抄表信息录入',

      headerRight: ({navigation}) => (
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            paddingLeft: 6,
          }}>
          <View>
            <TouchableOpacity
              activeOpacity={0.5}
              onPress={() => this.setModalVisible(true)}>
              <Image
                style={{height: 30, width: 30, marginRight: 5}}
                source={require('../img/search01.png')}
              />
            </TouchableOpacity>
          </View>

          <View>
            <TouchableOpacity activeOpacity={0.5}>
              <View style={styles.oneBox}>
                <SelfadaptModal
                  menuList={menuItem}
                  containerStyle={styles.oneBtn}
                  onPress={this.doSelect}>
                  <Image
                    style={{marginTop: 5, width: 20, height: 20}}
                    source={require('../img/more.png')}
                  />
                </SelfadaptModal>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      ),
    };
  };

  setModalVisible = visible => {
    this.setState({modalVisible: visible});
  };

  doSelect = (scene, value) => {
    //DeviceEventEmitter.emit('Tab', {});
    const {custCode, custName} = this.state;

    this.props.navigation.navigate(scene.flag, {
      custCode,
      custName,
      tabIndex: 2,
    });
  };

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false, //模态场景是否可见
      loading: true,
      custCode: '',
      custName: '',
      meterCode: '',
      natureName: '',
      priorReadingTime: '',
      priorReading: '',
      currReading: '',
      imgUrl: null,
    };
    this.navOptions = this.navOptions.bind(this);
    this.fetchData = this.fetchData.bind(this);
  }

  //组件挂载完成后执行的方法
  componentDidMount() {
    this.props.navigation.setOptions(this.navOptions());

    const {params} = this.props.route;
    console.log('entry route params:', params);
    const data = {
      bookId: params.bookId,
      currMonth: global.user.accountCycle.currMonth,
      flag: params.flag,
      orderNum: this.state.orderNum,
      custCode: params.custCode,
      pageVO: {
        sort: '',
        order: '',
      },
    };
    this.setState(
      {
        bookId: params.bookId,
        custCode: params.custCode,
        meterCode: params.meterCode,
        currMonth: global.user.accountCycle.currMonth,
        orderNum: '',
      },
      () => {
        //如果flag为last(接上次抄表)，则查询已抄记录是否为空
        if (params.flag == 'last') {
          this.getReadingData(
            params.bookId,
            global.user.accountCycle.currMonth,
            'hasRead',
          );
        } else {
          this.fetchData(data);
        }
      },
    );
  }

  //下载数据
  fetchData(data) {
    console.log(data);
    return new Promise((resolve, reject) => {
      let url = global.server.url + '/costMaster/selectOne';
      axiosInstance({
        method: 'post',
        url: url,
        data: data,
      })
        .then(res => {
          let datas = [];
          datas = datas.concat(res.rows);
          if (datas.length > 0) {
            resolve(datas[0]);
            this.setData(datas[0]);
          } else {
            if (data.pageVO.order == 'desc') {
              Toast.show('抱歉，已是第一户！');
            } else if (data.pageVO.order == 'asc') {
              Toast.show('抱歉，已是最后一户！');
            } else {
              this.setState({
                loading: false,
              });
              Alert.alert(
                '抱歉',
                '无记录。1、请确认本月是否生成抄表计划。2、检查查询条件。3、该表册是否存在用户。',
              );
            }
          }
        })
        .catch(err => {
          console.log(err);
          reject(err);
          Toast.show('发生异常，请联系系统管理员:' + err);
        });
    });
  }

  //按create_time降序排列已抄表数据
  getReadingData(bookId, currMonth, isRead) {
    let url = global.server.url + '/costMaster/selectHasReadPage';
    axiosInstance
      .post(url, {
        currMonth: currMonth,
        bookId: bookId,
        memo: isRead,
        pageVO: {
          sort: 'cm.modify_time',
          order: 'DESC',
        },
      })
      .then(res => {
        let datas = [];
        datas = datas.concat(res.records);
        //如果存在已抄表记录，则取第一条记录，即为上次抄表数据
        if (datas.length > 0) {
          this.setData(datas[0]);
        } else {
          const data = {
            bookId: this.state.bookId,
            custCode: this.state.custCode,
            meterCode: this.state.meterCode,
            orderNum: this.state.orderNum,
            currMonth: this.state.currMonth,
            pageVO: {
              sort: '',
              order: '',
            },
          };
          this.fetchData(data);
        }
      })
      .catch(err => {
        Toast.show('网络异常，请稍后再试！' + err);
      });
  }

  setData(datas) {
    this.setState({
      loading: false,
      custCode: datas.custCode,
      custName: datas.custName,
      orderNum: datas.orderNum,
      address: datas.address,
      tel: datas.tel,
      minimum: datas.minimum,
      natureName: datas.natureName,
      money: datas.money,
      meterCode: datas.meterCode,
      priorReadingTime: datas.priorReadingTime,
      priorReading: datas.priorReading,
      currReading: datas.currReading,
      originalReading: datas.currReading,
      quantity: datas.quantity,
      payDate: datas.payDate,
      months: datas.months,
      imgUrl: null,
    });
  }

  saveData() {
    let custCode = this.state.custCode;
    let meterCode = this.state.meterCode;
    let months = this.state.months;
    let currMonth = this.state.currMonth;
    let priorReading = parseFloat(this.state.priorReading);
    let currReading = parseFloat(this.state.currReading);
    let originalReading = parseFloat(this.state.originalReading);
    let quantity = parseFloat(this.state.quantity);

    if (!currReading) {
      Alert.alert('提示', '本期表码不能为空或为零！');
      return;
    }

    if (currReading <= priorReading) {
      Alert.alert('提示', '本期读数不能小于上期读数！');
      return;
    }

    if (originalReading > 0) {
      Alert.alert('提示', '本期已抄表，请点击清除按钮后，再抄表！');
      return;
    }

    const data = {
      custCode: custCode,
      months: months,
      currMonth: currMonth,
      meterCode: meterCode,
      priorReading: priorReading,
      quantity: quantity,
      currReading: currReading,
      status: 2,
    };
    this.update(data);
  }

  saveTips = () => {
    Alert.alert(
      '提示', //提示标题
      '确定要保存该数据吗？', //提示内容
      [
        {
          text: '确定',
          onPress: () => this.saveData(),
        },
        {
          text: '取消',
          onPress: () => console.log('点击取消'),
        },
      ], //按钮集合
    );
  };

  gotoPay() {
    let originalReading = parseFloat(this.state.originalReading);
    if (!originalReading) {
      Alert.alert('提示', '请抄表并保存后再缴费！');
      return;
    }
    let custCode = this.state.custCode;
    let currMonth = this.state.currMonth;
    let bookId = this.state.bookId;
    this.props.navigation.navigate('PayScene', {
      scene: 'Entry',
      bookId: bookId,
      custCode: custCode,
      currMonth: currMonth,
    });
  }

  //上一条或下一条
  jump(sort, order) {
    const {params} = this.props.route;
    const data = {
      bookId: this.state.bookId,
      custCode: this.state.custCode,
      orderNum: this.state.orderNum,
      currMonth: this.state.currMonth,
      pageVO: {
        sort: sort,
        order: order,
      },
    };

    this.fetchData(data);
  }

  setCurrReading(text) {
    //去掉以零开头的数字
    text = text.replace(/\b(0+)/gi, '');
    text = text.replace(/[^\d.]/g, '');
    //必须保证第一位为数字而不是.
    text = text.replace(/^\./g, '');
    //保证只有出现一个.而没有多个.
    text = text.replace(/\.{2,}/g, '.');
    //保证.只出现一次，而不能出现两次以上
    text = text.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');

    let minimum = this.state.minimum; //最低用水量
    let priorReading = this.state.priorReading;
    let quantity = Number(text) - Number(priorReading);

    if (quantity < minimum) {
      quantity = minimum;
    }

    this.setState(state => {
      return {
        quantity: quantity,
      };
    });

    this.setState(state => {
      return {
        currReading: text,
      };
    });
  }

  setMonths(text) {
    this.setState(state => {
      return {
        months: text,
      };
    });
  }

  clear = () => {
    let custCode = this.state.custCode;
    let meterCode = this.state.meterCode;
    let months = this.state.months;
    let currMonth = this.state.currMonth;
    let priorReading = Number(this.state.priorReading);
    let currReading = Number(this.state.currReading);

    if (!currReading) {
      Alert.alert('提示', '本期表码不能为空或为零！');
      return;
    }

    const params = {
      custCode: custCode,
      bookId: this.state.bookId,
      orderNum: this.state.orderNum,
      months: months,
      currMonth: this.state.currMonth,
      pageVO: {
        sort: '',
        order: '',
      },
    };
    this.fetchData(params)
      .then(result => {
        let payDate = result.payDate;
        if (payDate) {
          Alert.alert('本期已缴费，不允许清除！');
        } else {
          const data = {
            custCode: custCode,
            meterCode: meterCode,
            currMonth: currMonth,
            priorReading: priorReading,
            status: 0,
            currReading: 0,
          };

          this.update(data);

          this.setState({
            originalReading: '',
            currReading: '',
            quantity: '',
          });
        }
      })
      .catch(e => {});
  };

  update(data) {
    let url = global.server.url + '/costMaster/save';
    axiosInstance({
      method: 'post',
      url: url,
      data: data,
    })
      .then(res => {
        if (res.success) {
          this.setState({
            originalReading: data.currReading,
          });
          Toast.show('操作成功！');
        } else {
          Toast.show('操作失败！');
        }
      })
      .catch(err => {
        Toast.show('保存抄表数据时，请联系系统管理员:' + err);
      });
  }

  searchData() {
    const params = {
      bookId: this.state.bookId,
      currMonth: this.state.currMonth,
      custCode: this.state.cust_code,
      orderNum: this.state.orderNum,
      custName: this.state.cust_name,
      meterCode: this.state.meter_code,
      pageVO: {
        sort: '',
        order: '',
      },
    };
    this.fetchData(params)
      .then(result => {
        this.setState({
          cust_code: '',
          cust_name: '',
          meter_code: '',
        });
      })
      .catch(e => {});
    this.setModalVisible(false);
  }

  async checkCameraPermission(cb) {
    const permission = await check(PERMISSIONS.ANDROID.CAMERA);
    console.log('permission', permission);
    if (permission === 'granted') {
      cb();
    } else {
      const reqRes = await request(PERMISSIONS.ANDROID.CAMERA);
      console.log('req :', reqRes);
      if (reqRes == 'granted') {
        cb();
      }
    }
  }

  _onCameraClick() {
    this.checkCameraPermission(() => {
      this.takePicture();
    });
  }

  async takePicture() {
    launchCamera(
      {
        quality: 0.3,
        cameraType: 'back',
        saveToPhotos: true,
      },
      response => {
        console.log('res1:', response);
        const imageItem = response.assets[0];
        const {originalPath, fileName, uri, type} = imageItem;
        this.uploadImage(fileName, uri, type);
      },
    );
  }

  uploadImage = (name, imgUri, type) => {
    const {custCode, meterCode, currMonth} = this.state;
    this.setState({
      loading: true,
    });
    let param = [
      {name: 'custCode', data: custCode},
      {name: 'meterCode', data: meterCode},
      {name: 'currMonth', data: currMonth},
      {
        name: 'avatarfile',
        filename: name,
        type,
        data: RNFetchBlob.wrap(imgUri),
      },
    ];
    uploadFile(param, apiPath.uploadImage, res => {
      if (res.success) {
        console.log('img upload success:', res);
        this.setState({
          loading: false,
          imgUrl: res.data,
        });
      } else {
        console.log('img upload error:', err);
        this.setState({
          loading: false,
        });
      }
    });
  };

  deleteImage = () => {
    const url = getUrl(apiPath.deleteImage);
    const {currMonth, meterCode, custCode, imgUrl} = this.state;
    let imgPathArr = imgUrl.split('/');

    let param = {
      meterCode,
      currMonth,
      custCode,
      filePath: imgPathArr[imgPathArr.length - 1],
    };
    this.setState({loading: true});
    axiosInstance
      .post(url, param)
      .then(res => {
        this.setState({loading: false, imgUrl: null});
      })
      .catch(err => {
        this.setState({loading: false});
      });
  };

  render() {
    styles = getStyles();
    return (
      <KeyboardAwareScrollView keyboardShouldPersistTaps="always">
        <View style={styles.container}>
          {this.state.loading == true ? <Loading /> : null}
          <View style={styles.items}>
            <Text style={styles.textStyle}>水表编号:</Text>
            <Text style={styles.valueStyle}>{this.state.meterCode}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>客户名称:</Text>
            <Text style={styles.valueStyle}>{this.state.custName}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>联系电话:</Text>
            <Text style={styles.valueStyle}>{this.state.tel}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>账务月份:</Text>
            <Text style={styles.valueStyle}>{this.state.currMonth}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>上期表码:</Text>
            <Text style={[styles.valueStyle, {width: width - 90}]}>
              {this.state.priorReading}
            </Text>
            <Text style={styles.textStyle}>用水性质:</Text>
            <Text style={{width: width - 80}}>{this.state.natureName}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>抄表水量:</Text>
            <Text style={[styles.valueStyle, {width: width - 81}]}>
              {this.state.quantity}
            </Text>
            <Text style={styles.textStyle}>用户余额:</Text>
            <Text style={[styles.valueStyle]}>{this.state.money}</Text>
          </View>
          <View style={styles.items}>
            <Text style={styles.textStyle}>本期表码:</Text>
            <TextInput
              underlineColorAndroid="gray"
              placeholder="请输入本期表码"
              autoFocus={true}
              keyboardType="numeric"
              clearButtonMode="while-editing"
              style={[styles.inputStyle, {width: width - 81}]}
              value={this.state.currReading + ''}
              onChangeText={text => this.setCurrReading(text)}></TextInput>
            <Text style={styles.textStyle}>用水月数:</Text>
            <TextInput
              underlineColorAndroid="gray"
              keyboardType="numeric"
              style={styles.inputStyle}
              value={this.state.months + ''}
              onChangeText={text => this.setMonths(text)}></TextInput>
          </View>

          <View style={styles.items}>
            <TextButton title={'保存'} onPress={() => this.saveTips()} />
            <TextButton title={'缴费'} onPress={() => this.gotoPay()} />

            <TextButton title={'清除'} onPress={() => this.clear()} />

            <TextButton
              title={'上一户'}
              onPress={() => this.jump('<', 'desc')}
            />
            <TextButton
              title={'下一户'}
              onPress={() => this.jump('>', 'asc')}
            />
          </View>

          <View style={{paddingHorizontal: 5}}>
            {this.state.imgUrl ? (
              <View>
                <TextButton title={'删除图片'} onPress={this.deleteImage} />
                <Image
                  source={{uri: this.state.imgUrl}}
                  style={{width: 100, height: 100}}
                  resizeMode="contain"
                />
              </View>
            ) : (
              <TextButton
                title={'拍照'}
                onPress={() => this._onCameraClick()}
              />
            )}
          </View>

          <View style={{alignItems: 'center', flex: 1}}>
            <Modal
              animationType={this.state.animationType}
              transparent={this.state.transparent}
              visible={this.state.modalVisible}
              onRequestClose={() => {
                this.setModalVisible(false);
              }}>
              <View
                style={[
                  styles.modalContainer,
                  {backgroundColor: 'rgba(0, 0, 0, 0.5)'},
                ]}>
                <View
                  style={[
                    styles.innerContainer,
                    {backgroundColor: '#F0F8FF', padding: 20},
                  ]}>
                  <View style={styles.row}>
                    <View>
                      <Text style={styles.tips}>请输入一个或多个条件</Text>
                    </View>
                    <TextInput
                      style={styles.textInput}
                      placeholder={'用户名称'}
                      onChangeText={text => {
                        this.cust_name = text;
                        this.setState({cust_name: text});
                      }}
                      //输入框下划线
                      underlineColorAndroid={'transparent'}
                    />
                    <TextInput
                      style={styles.textInput}
                      placeholder={'用户编号'}
                      onChangeText={text => {
                        this.cust_code = text;
                        this.setState({cust_code: text});
                      }}
                      //输入框下划线
                      underlineColorAndroid={'transparent'}
                    />
                    <TextInput
                      style={styles.textInput}
                      placeholder={'水表编号'}
                      onChangeText={text => {
                        this.meter_code = text;
                        this.setState({meter_code: text});
                      }}
                      //输入框下划线
                      underlineColorAndroid={'transparent'}
                    />
                  </View>
                  <View style={styles.settingStyle}>
                    <Text
                      onPress={this.searchData.bind(this)}
                      style={styles.btnStyle}>
                      确定
                    </Text>
                    <Text
                      onPress={this.setModalVisible.bind(this, false)}
                      style={styles.btnStyle}>
                      关闭
                    </Text>
                  </View>
                </View>
              </View>
            </Modal>
          </View>
        </View>
      </KeyboardAwareScrollView>
    );
  }
}

const style = StyleSheet.create({
  saveBtn: {
    height: 35,
    width: 60,
    backgroundColor: 'green',
    margin: 4,
    justifyContent: 'center',
    borderRadius: 5,
  },
});
